package com.fengye.algorithms.leecode;

/**
 * @Author fengye
 * @Date 2023/4/24 11:24
 **/
public class MinimumSizeSubarraySum209 {
    public static void main(String[] args) {
        new MinimumSizeSubarraySum209().minSubArrayLen(4, new int[]{1,4,4});
    }
    public int minSubArrayLen(int target, int[] nums) {
        int min = Integer.MAX_VALUE;
        int len = nums.length;
        if(len == 0) {
            return 0;
        }

        int start = 0, end = 0;
        int sum = 0;
        while (end < len) {
            sum += nums[end];
            while (sum >= target) {
                // 取出最小的
                min = Math.min(min, end - start + 1);
                // 把最前面的减掉
                sum -= nums[start];
                // 指针向前
                start++;
            }
            // end向前
            end++;
        }

        return min == Integer.MAX_VALUE ? 0 : min;
    }

    // 超时
    public int minSubArrayLen1(int target, int[] nums) {
        int min = Integer.MAX_VALUE;
        for(int i=0;i < nums.length;i++) {
            int sum = nums[i];
            if(sum >= target) {
                min = 1;
                break;
            }
            for(int j=i-1;j>=0;j--) {
                sum += nums[j];
                if(sum >= target) {
                    min = Math.min(min, i-j+1);
                    break;
                }
            }
        }

        return min == Integer.MAX_VALUE ? 0 : min;
    }
}
